package com.example.demo.service;

import com.example.demo.mapper.ChatMessageMapper;
import com.example.demo.model.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class ChatService {
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Transactional
    public void saveMessage(ChatMessage message) {
        // 如果当前消息没有商品ID，获取最近的商品ID
        if (message.getProductId() == null) {
            Integer lastProductId = chatMessageMapper.getLastProductId(
                message.getSenderId(),
                message.getReceiverId()
            );
            message.setProductId(lastProductId);
        }
        
        // 无论是URL传入的还是数据库获取的商品ID，都更新该对话的所有消息
        if (message.getProductId() != null) {
            chatMessageMapper.updateLatestProductId(
                message.getSenderId(),
                message.getReceiverId(),
                message.getProductId()
            );
        }
        
        chatMessageMapper.insert(message);
    }

    public List<ChatMessage> getMessageList(Integer userId, Integer otherId) {
        // 标记消息为已读
        chatMessageMapper.updateMessageStatus(userId, otherId);
        return chatMessageMapper.getMessageList(userId, otherId);
    }

    public List<Map<String, Object>> getChatList(Integer userId) {
        return chatMessageMapper.getChatList(userId);
    }

    public void markMessagesAsRead(Integer receiverId, Integer senderId) {
        chatMessageMapper.updateMessageStatus(receiverId, senderId);
    }

    /**
     * 获取用户未读消息数量
     */
    public int getUnreadMessageCount(Integer userId) {
        return chatMessageMapper.getUnreadMessageCount(userId);
    }
} 